package com.heaton.videocar.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.widget.LinearLayout
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.model.BleDevice
import com.heaton.baselib.base.BaseActivity
import com.heaton.baselib.permission.IPermission
import com.heaton.baselib.utils.SPUtils
import com.heaton.videocar.App
import com.heaton.videocar.Constants
import com.heaton.videocar.R
import com.heaton.videocar.core.BleManager
import com.heaton.videocar.adapter.ConnectAdapter
import kotlinx.android.synthetic.main.activity_connect.*

class ConnectActivity : BaseActivity() {

    override fun layoutId() = R.layout.activity_connect
    private val bleManager by lazy { BleManager.get() }
    private lateinit var adapter: ConnectAdapter
    private var listDatas = mutableListOf<BleDevice>()
    private val handler = Handler(Looper.getMainLooper())

    override fun bindData() {
        bleManager.setBleCallback(this, bleCallback)
        initData()
        requestPermission()
    }

    private fun initData() {
        adapter = ConnectAdapter(
            baseContext,
            listDatas
        )
        val linearLayoutManager =
            LinearLayoutManager(baseContext, LinearLayoutManager.VERTICAL, false)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.addItemDecoration(DividerItemDecoration(baseContext, LinearLayout.VERTICAL))
        recyclerView.adapter = adapter
    }

    private fun requestPermission() {
        requestPermission(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            "需要蓝牙相关权限才能正常使用该APP哦!", object : IPermission(){
                override fun permissionGranted() {
                    checkBleStates()
                }
            })
    }

    private fun checkBleStates() {
        Ble.getInstance<BleDevice>().apply {
            if (!isSupportBle(context)) {
                toast("Not Support BLE")
                finish()
            }
            if (!isBleEnable) {
                turnOnBlueTooth(this@ConnectActivity)
            } else {
                bleManager.scan()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        listDatas.clear()
        val connectedDevice = bleManager.getConnectedDevice()
        connectedDevice?.let {
            listDatas.add(it)
        }
        adapter.notifyDataSetChanged()
        bleManager.scan()
    }

    override fun bindListener() {
        super.bindListener()
        tv_cancel.setOnClickListener { finish() }
        btn_refresh.setOnClickListener {
            val ble = Ble.getInstance<BleDevice>()
            if (ble.isScanning) return@setOnClickListener
            listDatas.clear()
            listDatas.addAll(ble.connectedDevices)
            adapter.notifyDataSetChanged()
            bleManager.scan()
        }

        adapter.setOnItemClickListener { parent, view, device, position ->
            if (device.isDisconnected) {
                bleManager.disconnect()
                handler.postDelayed({
                    bleManager.connect(device)
                }, 100)
            } else {
                bleManager.disconnect()
            }
        }
    }

    private fun addDevice(device: BleDevice?) {
        for (d in listDatas) {
            if (d.bleAddress == device?.bleAddress || d.bleName == device?.bleName) {
                return
            }
        }
        device?.let {
            listDatas.add(it)
            adapter.notifyDataSetChanged()
        }
    }

    private val bleCallback = object : BleManager.BleCallback() {

        override fun onScanStart() {
            super.onScanStart()
            startAnim()
        }

        override fun onScanEnd() {
            super.onScanEnd()
            stopAnim()
        }

        override fun onScan(device: BleDevice, rssi: Int, scanRecord: ByteArray?) {
            addDevice(device)
        }

        override fun onConnectionChanged(device: BleDevice) {
            when {
                device.isConnected -> {
                    //清除自动重连的设备
                    val address = SPUtils.get(baseContext, Constants.SP_CONNECTED_ADDRESS, "")
                    if (!TextUtils.isEmpty(address)){
                        val ble = Ble.getInstance<BleDevice>()
                        val bleDevice = ble.getBleDevice(address)
                        ble.autoConnect(bleDevice, false)
                    }
                    SPUtils.put(App.context, Constants.SP_CONNECTED_ADDRESS, device.bleAddress)
                }
                device.isDisconnected -> {}
            }
            adapter.notifyDataSetChanged()
        }

        override fun onConnectionException(device: BleDevice?, errorCode: Int) {
            adapter.notifyDataSetChanged()
        }

        override fun onConnectionTimeout(device: BleDevice?) {
            adapter.notifyDataSetChanged()
        }

        override fun onReady(device: BleDevice?) {
            toActivity(ControlActivity::class.java)
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Ble.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
//            toast("Please turn on Bluetooth to scan to the device")
        } else if (requestCode == Ble.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            bleManager.scan()
        }
    }

    private fun startAnim() {
        btn_refresh.text = "扫描中..."
    }

    private fun stopAnim() {
        btn_refresh.text = "扫描"
    }

    override fun finish() {
        super.finish()
        bleManager.stopScan()
    }
}